import axios from 'axios';
import { getToken } from './auth';

function setToken(config) {
  const token = getToken();
  if (token) {
    config.headers['blade-auth'] = token;
  }
}

const service = axios.create({
  timeout: 1000 * 60 * 5,
  withCredentials: true,
  validateStatus(status) {
    return status >= 200 && status <= 500;
  },
  baseURL: process.env.NODE_EVN === 'production' ? process.env.VUE_APP_REQUEST_BASE_URL : '/',
});

service.interceptors.request.use(
  config => {
    setToken(config);
    return config;
  },
  error => Promise.reject(error),
);

service.interceptors.response.use(
  res => {
    // if (res.status !== 200) {
    //   return Promise.reject('请求错误');
    // }
    if (res.data.code && res.data.code !== 200) {
      // window.message.error(res.data.msg);
      return Promise.reject(res.data.msg);
    }
    return res.data;
  },
  error => Promise.reject(error.message),
);

export default service;
